<template>
  <div class="detail-container">
    <div class="header">
      <el-steps style="width: 100%;" :active="currentStep" finish-status="success" align-center>
        <!-- 0----提交订单 -->
        <el-step title="提交订单" />
        <!-- 1----支付订单 -->
        <el-step title="支付订单" />
        <!-- 2----平台发货 -->
        <el-step title="平台发货" />
        <!-- 4----确认收货/订单完成 -->
        <el-step title="已送达，等待取货" />
        <!-- 5----完成评价 -->
        <el-step title="确认收货，完成交易" />
      </el-steps>
    </div>
    <div class="el-card is-never-shadow" style="margin-top: 15px;">
      <div class="el-card__body">
        <!-- <div class="operate-container"> -->
        <!-- <span  class="color-danger">当前订单状态：待发货</span> -->
        <!-- </div> -->
        <div style="margin-top: 20px;">
          <span class="font-small">基本信息</span>
        </div>
        <div class="table-layout">
          <div class="el-row">
            <div class="table-cell-title el-col el-col-5">订单编号</div>
            <div class="table-cell-title el-col el-col-5">用户账号</div>
            <div class="table-cell-title el-col el-col-5">支付方式</div>
            <div class="table-cell-title el-col el-col-5">支付时间</div>
            <div class="table-cell-title el-col el-col-4">修改时间</div>
          </div>
          <div class="el-row">
            <div class="table-cell el-col el-col-5">{{ order.orderNo }}</div>
            <div class="table-cell el-col el-col-5">{{ order.memberId }}</div>
            <div class="table-cell el-col el-col-5">{{ order.payType }}</div>
            <div class="table-cell el-col el-col-5">{{ order.payTime }}</div>
            <div class="table-cell el-col el-col-4">{{ order.updateTime }}</div>
          </div>

        </div>
        <div style="margin-top: 20px;">
          <span class="font-small">收货人信息</span>
        </div>
        <div class="table-layout">
          <div class="el-row">
            <div class="table-cell-title el-col el-col-8">收货人</div>
            <div class="table-cell-title el-col el-col-8">手机号码</div>
            <div class="table-cell-title el-col el-col-8">收货地址</div>
          </div>
          <div class="el-row">
<!--            <div class="table-cell el-col el-col-8">{{ memberInfo?.name || '未获取到会员信息' }}</div>-->
<!--            <div class="table-cell el-col el-col-8">{{ memberInfo?.phone || '未获取到会员信息' }}</div>-->
<!--            <div class="table-cell el-col el-col-8">{{ memberInfo?.address || '未获取到会员信息' }}</div>-->
            <div class="table-cell el-col el-col-8">{{ order.receiverName }}</div>
            <div class="table-cell el-col el-col-8">{{ order.receiverPhone  }}</div>
            <div class="table-cell el-col el-col-8">{{ order.receiverAddrDetail  }}</div>
          </div>
        </div>
        <div style="margin-top: 20px;">
          <span class="font-small">商品信息</span>
        </div>
        <div style="width: 100%; margin-top: 20px;">
          <el-table :data="orderItems" border style="width: 100%" :header-cell-style="{ textAlign: 'center' }"
                    :cell-style="{ textAlign: 'center' }">
            <el-table-column prop="itemCoverImg" label="商品主图" width="180" align="center">
              <template #default="scope">
                <div class="row-image" :style="'background-image:url(' + scope.row.itemCoverImg + ')'">
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="itemName" label="商品名称" width="120" />
            <el-table-column prop="brandName" label="品牌" width="80" />
            <el-table-column label="价格" width="120">
              <template #default="scope">
                {{ scope.row.itemPrice }}
              </template>
            </el-table-column>
            <el-table-column prop="itemDescription" label="商品描述" width="240" />
            <el-table-column prop="number" label="购买数量" width="100" />
            <el-table-column prop="totalPrice" label="小计" width="120" />
          </el-table>
        </div>
        <div style="float: right; margin: 20px;">
          合计：<span class="color-danger">{{oldPrice.toFixed(2)}}元</span>
        </div>
        <div style="margin-top: 60px;">
          <span class="font-small">费用信息</span>
        </div>
        <div class="table-layout">
          <div class="el-row">
            <div class="table-cell-title el-col el-col-6">商品原价之和</div>
            <div class="table-cell-title el-col el-col-6">折扣金额</div>
            <div class="table-cell-title el-col el-col-6">活动优惠</div>
            <div class="table-cell-title el-col el-col-6">应付款金额</div>
          </div>
          <div class="el-row">
            <div class="table-cell el-col el-col-6">{{oldPrice.toFixed(2)}}元</div>
            <div class="table-cell el-col el-col-6">-{{countPrice.toFixed(2)}}元</div>
            <div class="table-cell el-col el-col-6">-{{comPrice.toFixed(2)}}元</div>
            <div class="table-cell color-danger el-col el-col-6" >{{price}}元</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { Plus, Edit, Search, Refresh, Delete, CircleClose, CircleCheck } from '@element-plus/icons-vue'
import { ref, onMounted, watch } from 'vue';
import { useRoute } from 'vue-router';
import { findById,findAll } from '@/api/OrderApi';
import { getOrderItem } from '@/api/OrderItemApi';
import { findById as findOrderLogisticsById } from '@/api/OrderLogisticsApi';
import { findById as findMemberById } from '@/api/MemberApi';

const route = useRoute();
const currentStep = ref(0);
const order = ref({}); // 响应式订单对象
const orderItems = ref([]); // 响应式订单项数组
const orderLogistics = ref({});
const memberInfo = ref({}); // 会员信息
const price = ref(0);
const oldPrice = ref(0);
const countPrice = ref(0);
const comPrice = ref(0);

// 加载订单详情的主要函数
const loadOrderDetail = async (id) => {
  await findAll();
  try {

    // 1. 获取订单基本信息 这里的id是订单id
    // console.log("asdasd"+id)
    const orderResp = await findById(id);
    console.log("订单信息12312312响应:", orderResp);

    if (orderResp && orderResp.data) {

      // 处理订单数据
      const orderData = orderResp.data;
      orderData.payment = orderData.totalPay ? orderData.totalPay.toFixed(2) : '0.00';
      order.value = orderData; // 响应式更新
      // console.log("订单信息:", order.value);

      price.value = orderData.totalPay ? parseFloat(orderData.totalPay) : 0;

      // 设置订单状态步骤
      if (orderData.status === '0' || orderData.status === 0) {
        currentStep.value = 1;
      } else if (orderData.status === '1' || orderData.status === 1) {
        currentStep.value = 2;
      } else if (orderData.status === '2' || orderData.status === 2) {
        currentStep.value = 3;
      } else if (orderData.status === '3' || orderData.status === 3) {
        currentStep.value = 4;
      } else if (orderData.status === '4' || orderData.status === 4) {
        currentStep.value = 5;
      }

      // 2. 获取订单项信息 - 等待订单基本信息获取完成后再执行
      try {
        // 检查orderData.id是否存在
        if (!orderData.id) {
          console.error("订单ID不存在");
          return;
        }
        
        const itemsResp = await getOrderItem(orderData.id);
        // console.log("订单项123133信息响应:", itemsResp);

        // 重置价格计算
        oldPrice.value = 0;
        countPrice.value = 0;
        comPrice.value = 0;

        if (itemsResp && itemsResp.data) {
          if (Array.isArray(itemsResp.data)) {
            orderItems.value = itemsResp.data.map(item => {
              const itemPrice = item.dealPrice ? parseFloat(item.dealPrice) : 0;
              const itemCount = item.count || 0;
              const subtotal = item.subtotal ? parseFloat(item.subtotal) : itemPrice * itemCount;

              // 累加原价
              oldPrice.value += itemPrice * itemCount;

              return {
                itemCoverImg: item.goodPic || '',
                itemName: item.goodName || '',
                brandName: item.brandName || '',
                itemDescription: item.goodDescription || '',
                number: itemCount,
                itemPrice: itemPrice.toFixed(2),
                totalPrice: subtotal.toFixed(2)
              };
            });

            // 计算折扣金额
            countPrice.value = oldPrice.value - price.value;
            console.log("处理后的订单项:", orderItems.value);
            console.log("价格信息:", {
              oldPrice: oldPrice.value,
              price: price.value,
              countPrice: countPrice.value
            });
          }
        }
      } catch (error) {
        console.error("获取订单项失败:", error);
      }

      // 3. 获取物流信息
      try {
        const logisticsResp = await findOrderLogisticsById(id);
        orderLogistics.value = logisticsResp.data;
        console.log("订单物流信息:", orderLogistics.value);
      } catch (error) {
        console.error("获取订单物流信息失败:", error);
      }
    }
  } catch (error) {
    console.error("获取订单信息失败:", error);
  }
};

// 监听路由参数变化
watch(
  () => route.params.id,
  (newId, oldId) => {
    if (newId && newId !== oldId) {
      loadOrderDetail(newId);
    }
  }
);

onMounted(() => {
  const id = route.params.id;
  // console.log("订单ID:", id);

  if (id) {
    loadOrderDetail(id);
  } else {
    console.error("未获取到订单ID");
  }
});
</script>
<style scoped>
.row-image {
  height: 80px;
  background-position: center center;
  background-repeat: no-repeat;
  background-size: contain;

}

.detail-container {
  width: 80%;
  padding: 20px;
  margin: 20px auto;
}

.el-step__description.is-success {
  color: #67c23a;
}

.el-step__title.is-process {
  color: #67c23a;
}

.el-card {
  border: 1px solid #ebeef5;
  background-color: #fff;
  color: #303133;
  transition: .3s;
}

.el-card,
.el-message {
  border-radius: 4px;
  overflow: hidden;
}

.el-card__body {
  padding: 20px;
}

.operate-container {
  background: #f2f6fc;
  height: 80px;
  margin: -20px -20px 0;
  line-height: 80px;
}

.font-small {
  font-size: 14px;
  color: #606266;
}

.table-layout {
  margin-top: 20px;
  border-left: 1px solid #dcdfe6;
  border-top: 1px solid #dcdfe6;
}

.table-cell-title {
  background: #f2f6fc;
  color: #303133;
}

.table-cell-title,
.table-cell {
  border-right: 1px solid #dcdfe6;
  border-bottom: 1px solid #dcdfe6;
  padding: 10px;
  font-size: 14px;
  text-align: center;
}

.el-col-4 {
  width: 16.66667%;
}

.table-cell {
  height: 60px;
  line-height: 40px;
  color: #606266;
  overflow: hidden;
}

.table-layout {
  margin-top: 20px;
  border-left: 1px solid #dcdfe6;
  border-top: 1px solid #dcdfe6;
}

.el-col-6 {
  width: 25%;
}

element.style {
  float: right;
  margin: 20px;
}

.color-danger {
  color: #f56c6c;
}
</style>